package com.ruoyi.web.controller.word;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ErrorCode;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.baidu.TransWebApi;
import com.ruoyi.common.domain.word.CommonRa;
import com.ruoyi.common.domain.word.vo.CommonRaExcelVO;
import com.ruoyi.word.service.ICommonRaService;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ra")
public class CommonRaController extends BaseController {

    @Autowired
    private ICommonRaService biz;

    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public R find(String sort, String order, String page, String size, String keyword, String word, Integer type) {
        try{
            if(StringUtils.isEmpty(sort)) {
                sort = "add_time"; order = "desc";
            }
            startPage();
            return R.data(new PageInfo<>(biz.findByWhereStr(buildParam(keyword, word, type), sort, order)));
        }catch(Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }

    private String buildParam(String keyword, String word, Integer type){
        StringBuilder whereStr = new StringBuilder("1 = 1 ");
        if(StringUtils.isNotEmpty(keyword)) {
            whereStr.append(" and name like '%" + keyword + "%'");
        }
        if(StringUtils.isNotEmpty(word)) {
            whereStr.append(" and name = '" + word + "'");
        }
        if(type != null) {
            whereStr.append(" and type=" + type);
        }
        buildTimeQuerySql(whereStr, "update_time");
        return whereStr.toString();
    }

    @PostMapping("/save")
    public R save(@RequestBody CommonRa record){
        try {
            if(StringUtils.isEmpty(record.getName())) {
                return R.fail(ErrorCode.INVALID_PARAMETERS);
            }
            if(biz.exists(record.getName(), record.getType())) {
                return R.fail(ErrorCode.ALREADY_EXISTS);
            }
            Date date = new Date();
            record.setAddTime(date);
            record.setUpdateTime(date);
            return R.data(biz.save(record));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }

    @PutMapping("/update")
    public R update(@RequestBody CommonRa record){
        try {
            if(record.getId() == null || StringUtils.isEmpty(record.getName())) {
                return R.fail(ErrorCode.INVALID_PARAMETERS);
            }
            return R.data(biz.update(record));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }

    @DeleteMapping("/del/{id}")
    public R delete(@PathVariable Long id){
        try {
            return R.data(biz.delete(id));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }

    @PostMapping("/reBuildRa")
    public R reBuildRa(){
        try {
            return R.data(biz.buildRa());
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response, String id, String sort, String order, String keyword, String word, Integer type) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("词根词缀", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            if(StringUtils.isEmpty(sort)) {
                sort = "p.add_time";
            }else{
                sort = "p." + sort;
            }
            List<CommonRa> data = biz.findByWhereStr(buildParam(keyword, word, type), sort, "desc");
            EasyExcel.write(response.getOutputStream(), CommonRaExcelVO.class).autoCloseStream(Boolean.FALSE).sheet("词根词缀")
                    .doWrite(toExcelVo(data));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSON.toJSONString(R.fail()));
        }
    }

    public static void main(String[] args) throws IOException {
//        String  templateFileName = "E:\\work\\小柿子\\yamc\\tmp\\import-test.xlsx";
//
//        FileInputStream fis = new FileInputStream(templateFileName);
//        Workbook workbook = new XSSFWorkbook(fis);
//        Sheet sheet = workbook.getSheetAt(0);

        // 获取工作表中所有的图片
//        List<XSSFPictureData> pictures = ((XSSFWorkbook) workbook).getAllPictures();
//        for (XSSFPictureData picture : pictures) {
//
//            System.out.println("Picture name: " + picture.suggestFileExtension() + ", type: " + picture.getMimeType());
//            // 你可以根据需要对图片数据进行进一步处理，例如保存到文件或数据库中
//        }

//        workbook.close();
//        fis.close();


        try (FileInputStream fis = new FileInputStream("E:\\work\\小柿子\\yamc\\tmp\\word-data.xlsx")) {
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            XSSFSheet sheet = workbook.getSheetAt(0);

            // 获取工作表中的绘图对象
            XSSFDrawing drawing = sheet.getDrawingPatriarch();
            if (drawing != null) {
                // 获取所有的形状
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    if (shape instanceof XSSFPicture) {
                        XSSFPicture picture = (XSSFPicture) shape;
                        XSSFClientAnchor anchor = picture.getPreferredSize();

                        // 获取图片对应的单元格位置
                        int row1 = anchor.getRow1();
                        int col1 = anchor.getCol1();

                        System.out.println("图片位于单元格: (" + col1 + ", " + row1 + ")");

                        // 可以进一步处理，例如获取图片数据等
                        XSSFPictureData pictureData = (XSSFPictureData) picture.getPictureData();
                        System.out.println("图片名称: " + pictureData.getPictureType());
                        System.out.println("图片类型: " + pictureData.getMimeType());

                        FileOutputStream fos = new FileOutputStream("E:\\work\\小柿子\\yamc\\tmp\\" + row1 + "_" + col1 + ".jpg");
                        fos.write(pictureData.getData());
                        fos.close();
                    }
                }
            }

            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<CommonRaExcelVO> toExcelVo(List<CommonRa> data){
        List<CommonRaExcelVO> result = new ArrayList<>(data.size());
        data.stream().forEach(d -> {
            CommonRaExcelVO vo = new CommonRaExcelVO();
            BeanUtils.copyProperties(d, vo);
            result.add(vo);
        });
        return result;
    }

}
